package com.medvalley.tcm.controller;

import com.google.common.collect.Maps;
import com.medvalley.tcm.base.Constants;
import com.medvalley.tcm.base.Result;
import com.medvalley.tcm.cache.RedisCache;
import com.medvalley.tcm.domain.Doctor;
import com.medvalley.tcm.service.DoctorService;
import com.medvalley.tcm.service.SMSService;
import com.medvalley.tcm.service.impl.AliOSSService;
import com.medvalley.tcm.vo.inputvo.SearchDoctorInputVo;
import com.medvalley.tcm.vo.outputvo.DoctorPageOutputVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @author linsong
 * @date 2019/4/21 15:32
 **/
@RestController
@RequestMapping("/doctor")
@Api(value = "医师相关接口")
public class DoctorController extends BaseController {
    private static Logger LOGGER = LoggerFactory.getLogger(DoctorController.class);

    @Value("${oss.headicon.bucketName}")
    private String headIconBucketName;

    @Autowired
    private SMSService smsService;

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private AliOSSService aliOSSService;

    @Autowired
    private RedisCache redisCache;

    @ApiOperation(value = "注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result register(@RequestParam String phone, @RequestParam String smsCode) {
        boolean result = smsService.validateCode(phone, smsCode);
        if (result) {
            Doctor doctor = doctorService.login(phone);
            String token = this.generateToken(phone);
            Map<String, Object> retMap = Maps.newHashMap();
            retMap.put("token", token);
            retMap.put("doctorInfo", doctor);
            return success(retMap);
        } else {
            return error("验证码错误");
        }
    }

    @ApiOperation(value = "更新资料")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result update(Doctor doctor) {
        doctorService.updateDoctor(doctor);
        return success(doctor);
    }

    @ApiOperation(value = "保存认证")
    @RequestMapping(value = "/save/credential", method = RequestMethod.POST)
    public Result saveCredential(String imageUrl, HttpServletRequest request) {
        String phone = getSessionPhone(request);
        doctorService.saveCredential(phone, imageUrl);
        return success();
    }

    @ApiOperation(value = "上传头像")
    @RequestMapping(value = "/headIcon", method = RequestMethod.POST)
    public Result uploadHeadIcon(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String sessionPhone = getSessionPhone(request);
        try {
            String fileName = file.getOriginalFilename();
            String suffix = "";
            if (fileName.lastIndexOf(".") > 0) {
                suffix = fileName.substring(fileName.lastIndexOf("."));
            }
            long currentTime = System.currentTimeMillis();
            String uri = aliOSSService.upload(file.getInputStream(), sessionPhone + "-head-" + currentTime + suffix,
                    headIconBucketName);
            doctorService.setHeadIcon(sessionPhone, uri);
            return success(uri);
        } catch (IOException e) {
            LOGGER.error("上传头像错误", e);
            return error("上传头像错误");
        }
    }

    @ApiOperation(value = "获取资料")
    @RequestMapping(value = "/info", method = RequestMethod.POST)
    public Result doctorInfo(long id, HttpServletRequest request) {
        Doctor doctor = doctorService.getById(id);
        return success(doctor);
    }

    @ApiOperation(value = "搜索医生")
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result searchDoctor(@ModelAttribute SearchDoctorInputVo searchDoctorInputVo) {
        DoctorPageOutputVo doctorPageOutputVo = doctorService.searchDoctor(searchDoctorInputVo);
        return success(doctorPageOutputVo);
    }

    private String generateToken(String phone) {
        String token = DigestUtils.md5DigestAsHex(phone.getBytes());
        redisCache.setValue(Constants.SESSION_PREFIX + token, phone);
        return token;
    }

}
